<?php

namespace app\api\service;

use app\api\model\AdminModel;
use function PHPSTORM_META\elementType;
use think\Log;
use think\Request;
use think\Validate;

class LogService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 插入系统日志
     * Params: msg 插入日志信息   isJson 插入格式 true Json格式   logName 日志文件名称
     */
    public function writeLogInfo($msg = [], $logName = 'ErrorLog', $isJson = true)
    {
        if ($isJson)
        {
            Log::write(json_encode($msg), $logName);
        }else{
            Log::write($msg, $logName);
        }
        return true;
    }

    /**
     * 插入数据日志
     * @param log array
     */
    public function writeSysLog($log)
    {
        $Validate = new Validate([
            'operation' => 'require',
            'title' => 'require',
            'content' => 'require',
        ]);
        if (!$Validate->check($log))
        {
            $this->error($Validate->getError());
        }

        $saveData = [
            'admin_id' => $this->uid,
            'username' => AdminModel::getInstance()->value([
                'id' => ['eq', $this->uid]
            ]),
            'url' => $log['operation'],
            'title' => $log['title'],
            'content' => json_encode($log['content']),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'useragent' => $_SERVER['HTTP_USER_AGENT'],
            'createtime' => time(),
        ];
        return AdminModel::getInstance()->setLog($saveData);
    }

}